﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Domain.Repository;
using WMS.FC.Domain.Service.System.Interface;

namespace WMS.FC.Domain.Service.System
{
    public class AddDataService : ServiceBase, IAddDataService
    {
        protected readonly ISystemRepository systemRepository;
        protected readonly IMenuRepository menuRepository;

        public AddDataService(
            ILogger<ServiceBase> logger,
            IOptions<WmsSettings> options,
            IMapper mapper,
            ISystemRepository systemRepository,
            IMenuRepository menuRepository)
            : base(logger, options, mapper)
        {
            this.systemRepository = systemRepository;
            this.menuRepository = menuRepository;
        }

        public async Task<ActionResultBase> AddData(string menuId, Dictionary<string, string> value, UserInfo userInfo)
        {
            var result = new ActionResultBase("新增数据");
            try
            {
                if (string.IsNullOrWhiteSpace(menuId))
                    return result.ArgumentError("菜单ID不能为空");

                var menuPO = await menuRepository.GetMenu(Convert.ToInt64(menuId));
                if (menuPO == null)
                    return result.DbError($"ID:{menuId},菜单数据未找到");

                if (string.IsNullOrWhiteSpace(menuPO.Sql))
                    return result.BusinessError($"菜单:{menuPO.NameCN},sql语句为空");

                var parameters = new Dictionary<string, object>();
                foreach (var item in value)
                {
                    if (item.Value.StartsWith("DateTime:"))
                    {
                        parameters.Add(item.Key, Convert.ToDateTime(item.Value.Replace("DateTime:", "")));
                    }
                    else
                    {
                        parameters.Add(item.Key, item.Value);
                    }
                }

                var count = await systemRepository.ExecuteNoQuery(menuPO.Sql, userInfo, parameters);
                if (count == 0)
                    return result.DbError("新增数据0条");

                result.Message = $"新增数据成功";
            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }
    }
}
